package com.zeny.express.framework.log.log4j;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zeny.express.framework.log.entity.ActionLogEntity;
import com.zeny.express.framework.log.entity.BusinessLog;
import com.zeny.express.framework.log.service.LogPersistenceService;

/**
 * Database Log Appender
 * 
 * @author zhuwei
 * @date 2013年10月12日 上午11:40:57
 */
public class DBLogAppender extends AppenderSkeleton implements Appender {

	/**
	 * File Logger
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 日志持久化服务
	 */
	private LogPersistenceService logPersistenceService;

	/**
	 * 日志插入
	 * 
	 * @author zhuwei
	 * @date 2013年10月12日 上午11:55:48
	 * @see org.apache.log4j.AppenderSkeleton#append(org.apache.log4j.spi.LoggingEvent)
	 */
	protected void append(LoggingEvent event) {
		Object msg = event.getMessage();
		try {
			if (msg instanceof ActionLogEntity) {
				logPersistenceService.saveActionLog((ActionLogEntity) msg);
			} else if (msg instanceof BusinessLog) {
				logPersistenceService.saveBusinessLog((BusinessLog) msg);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			logger.debug(ToStringBuilder.reflectionToString(msg));
		}
	}

	public void close() {
		this.closed = true;
	}

	public boolean requiresLayout() {
		return false;
	}

	/**
	 * @param logPersistenceService
	 */
	public void setLogPersistenceService(
			LogPersistenceService logPersistenceService) {
		this.logPersistenceService = logPersistenceService;
	}

}
